<template>
  <div class="login">
    <div class="logo-title">
      <router-link to="/">
        <div class="flex flex-row items-center">
          <img src="@/assets/logo/logo.png" alt="" />
          <span>{{title}}</span>
        </div>
      </router-link>
      <Language class="cursor ml-10" :color-style="`var(--el-color-primary)`"/>
    </div>
    <div class="login-content">
      <div class="login-bg"/>
      <!--      <img class="form-head-line" src="@/assets/images/form-line.png" alt="">-->
      <div class="login-title">{{ proxy.$t('login.title') }}</div>
      <el-form
          ref="formRef"
          :model="formState"
          class="login-form"
          :rules="rules"
          label-position="left"
          @keyup.enter="submit"
      >
        <el-form-item prop="username">
          <el-input
              v-model="formState.username"
              :placeholder="proxy.$t('login.username')"
              clearable
          >
            <template #prefix>
              <img style="width: 18px; height: 18px; " src="@/assets/images/user.png" alt="">
              <div class="login-divider"/>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              type="password"
              v-model="formState.password"
              :placeholder="proxy.$t('login.password')"
              show-password
              clearable
          >
            <template #prefix>
              <img style="width: 18px; height: 18px; " src="@/assets/images/password.png" alt="">
              <div class="login-divider"/>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <div class="login-code">
            <el-input
                v-model="formState.code"
                :placeholder="proxy.$t('login.code')"
                :maxlength="4"
                clearable
                @input="limitUpperCase"
            >
              <template #prefix>
                <img style="width: 18px; height: 18px; " src="@/assets/images/code.png" alt="">
                <div class="login-divider"/>
              </template>
            </el-input>
            <div class="code-right" v-loading="captchaLoading">
              <img
                  v-if="imgUrl"
                  :src="imgUrl"
                  alt=""
                  @click="getCaptcha"
              />
              <el-button v-else link @click="getCaptcha">{{ proxy.$t('login.refresh') }}</el-button>
            </div>
          </div>
        </el-form-item>
        <!--        <div class="login-form-bottom">-->
        <!--          <router-link to="/register">立即注册</router-link>-->
        <!--          <router-link to="/resetPassword">忘记密码?</router-link>-->
        <!--        </div>-->
        <el-form-item>
          <el-button
              type="primary"
              :disabled="loading"
              class="login-form-button"
              @click="submit"
          >
            {{ loading ? proxy.$t('login.signIn') : proxy.$t('login.login') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="footer">
      <Footer :color="'#959595'"/>
    </div>
  </div>
</template>

<script setup>
import {LoginApi} from '@/api/login'
import {useRouter} from 'vue-router'
import {loginUserStoreHook} from '@/stores/modules'
import Footer from '@/components/Footer/index.vue'
import {CommonApi} from '@/api/common.js'
import useCurrentInstance from '@/hooks/useCurrentInstance.js'
import {JSEncrypt} from 'jsencrypt';
import {CacheUtil} from '@/utils/cacheUtil.js'
import Language from '@/components/Language/index.vue'
import {onMounted} from "vue";
import {DefaultThemeColor} from "@/common/constant.js";
import {changeColor} from "@/utils/color.js";

const {proxy} = useCurrentInstance();
const loginUserStore = loginUserStoreHook()
const router = useRouter()
const formRef = ref()
const imgUrl = ref('')
const loading = ref(false)
const captchaLoading = ref(false)
const redirect = ref()
const formState = reactive({
  username: '',
  password: '',
  code: '',
  generateId: '',
  sessionGenerateId: ''
})
const rules = reactive({
  username: [{required: true, trigger: 'blur', message: proxy.$t('login.username')}],
  password: [{required: true, trigger: 'blur', message: proxy.$t('login.password')}],
  code: [{required: true, trigger: 'blur', message: proxy.$t('login.code')}]
})
const title = import.meta.env.VITE_APP_TITLE;

function limitUpperCase(event) {
  formState.code = event.toUpperCase()
}

// 获取验证码
function getCaptcha() {
  captchaLoading.value = true
  LoginApi.getCaptcha().then(({data}) => {
    captchaLoading.value = false
    const {baseImage, generateId} = data
    imgUrl.value = 'data:image/gif;base64,' + baseImage
    formState.generateId = generateId
  }).catch(error => {
    console.log(error)
    captchaLoading.value = false
    imgUrl.value = ''
    formState.generateId = ''
  })
}

async function submit() {
  if (!formRef.value) return;
  formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      CommonApi.getPublicKey().then((result) => {
        if (!result || result.length === 0) {
          // proxy.$message.error("登录失败,请联系管理员!");
          throw new Error();
        } else {
          const {publicKey, sessionGenerateId} = result;
          CacheUtil.setSessionGenerateId(sessionGenerateId);
          const encryptor = new JSEncrypt();
          encryptor.setPublicKey(publicKey);
          const formData = {};
          Object.assign(formData, formState);
          formData.sessionGenerateId = sessionGenerateId;
          formData.password = encryptor.encrypt(formState.password);
          loginUserStore.login(formData).then(res => {
            loading.value = false
            if (null != res) {
              router.push({path: redirect.value || '/'})
              proxy.$notify({
                title: '系统提示',
                message: '欢迎回来!',
                type: 'success',
              })
            } else {
              formState.code = ''
              formState.generateId = ''
              getCaptcha()
            }
          }).catch(() => {
            loading.value = false
            // 登录失败刷新验证码
            formState.code = ''
            formState.generateId = ''
            getCaptcha()
          })
        }
      }).catch(() => {
        loading.value = false;
        proxy.$message.error("登录失败,请联系管理员!");
      });
    } else {
      console.log("error submit!", fields);
    }
  })
}

watch(
    () => router.currentRoute.value.path,
    v => {
      console.log(v)
      redirect.value = router.currentRoute.value.query.redirect
    },
    {immediate: true, deep: true}
)
const theme = ref(DefaultThemeColor);
onMounted(() => {
  let setting = CacheUtil.getSystemSetting()
  if (setting) {
    theme.value = setting['themeClass'] ? setting['themeClass'] : DefaultThemeColor;
  }
  changeColor('primary',theme.value)
})
getCaptcha()
</script>

<style scoped lang="scss">
.login {
  width: 100%;
  height: 100vh;
  background: url("@/assets/images/bg-login.png") no-repeat;
  background-size: 100% 100%;
  display: flex;
  align-items: center;
}

.login-content {
  border-radius: 18px;
  width: 426px;
  height: auto;
  position: absolute;
  left: 60.43%;
  top: 25%
}

.login-bg {
  background: #FFFFFF;
  border-radius: 18px;
  opacity: 0.6;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 9;
}

.form-head-line {
  position: absolute;
  left: 21px;
  top: -29px;
}

.login-title {
  font-family: 'PingFang Bold', sans-serif;
  font-weight: bold;
  font-size: 24px;
  color: #f5f5f5;
  width: 100%;
  text-align: left;
  margin-top: 36px;
  line-height: 9px;
  margin-bottom: 30px;
  margin-left: 40px;
  position: relative;
  z-index: 99;
}

.login-form {
  border-radius: 18px;
  opacity: 1;
  padding: 0 10%;
  box-sizing: border-box;
  position: relative;
  z-index: 99;

  .el-input {
    font-size: 14px;
    font-weight: 400;
    height: 40px;
  }
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 0;
}

.el-form-item {
  margin-bottom: 16px;
}

:deep(.el-input__inner) {
  font-family: 'PingFang', sans-serif;
  font-weight: 400;
  font-size: 14px;
  color: #959595;
}

.login-divider {
  width: 1px;
  height: 16px;
  background: #CBCBCB;
  margin: 0 12px;
}

.login-code {
  display: flex;
  align-items: center;
}

.code-right {
  width: 99px;
  height: 40px;
  background: #FFFFFF;
  border-radius: 5px;
  margin-left: 15px;
  cursor: pointer;

  img {
    width: 90px;
    height: 21px;
    border-radius: 5px;
    margin-top: 10px;
  }

  :deep(.el-button > span) {
    font-family: 'PingFang Medium', sans-serif;
    font-size: 12px;
    color: #2f54eb;
  }
}

.login-form-bottom {
  width: 100%;
  height: 13px;
  margin-bottom: 42px;
  display: flex;
  justify-content: space-between;

  a {
    color: #959595;
    font-family: 'PingFang', sans-serif;
    font-weight: 400;
    font-size: 14px;
  }
}

.login-form-button {
  width: 100%;
  height: 40px;
  //  background: linear-gradient(242deg, #5893FE 0%, #409EFF 100%,);
  border-radius: 5px;
  margin-bottom: 15px;
  margin-top: 20px;
}

:deep(.el-button > span) {
  font-family: 'PingFang Medium', sans-serif;
  font-weight: 500;
  font-size: 16px;
  color: #FFFFFF;
}

.footer {
  width: 100%;
  position: absolute;
  bottom: 0;
}

.el-button--primary {
  border: 1px solid rgba(0, 0, 0, 0); /* 完全透明 */
}

:deep(.el-loading-spinner .circular) {
  margin-top: 10px;
  width: 25px;
  height: 25px;
}
</style>
